package cn.xiehang.SoundSight;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.OpenableColumns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.Manifest;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.annotation.NonNull;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SecondFragment extends Fragment {
    // 定义常量
    private static final int REQUEST_CODE_AUDIO_PICK = 1001;
    private static final int REQUEST_CODE_PERMISSION = 1002;
    private static final String URL=SeverURL.URL+"/upload_audio";

    private Button btnSelectAudio, btnRecordAudio, btnUpload,btnShare;
    private ImageView imageView;
    private ProgressBar progressBar;
    private TextView tvStatus;

    private File audioFile;
    private File outputFile;
    Button btnVoice;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_second, container, false);

        // 初始化视图
        btnSelectAudio = view.findViewById(R.id.btnSelectAudio);
        btnUpload = view.findViewById(R.id.btnUpload);
        imageView = view.findViewById(R.id.SoundSightimageView);
        progressBar = view.findViewById(R.id.progressBar);
        tvStatus = view.findViewById(R.id.tvStatus);
        btnShare = view.findViewById(R.id.secondFragmentShareButton);
        btnVoice = view.findViewById(R.id.voiceButton);

        // 选择音频文件
        btnSelectAudio.setOnClickListener(v -> {

            if (ContextCompat.checkSelfPermission(requireContext(),
                    Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_CODE_PERMISSION);
            } else {
                openFilePicker();
            }
        });
        btnVoice.setOnClickListener(v -> {
            // 播放选择的音频文件
            if (audioFile == null) {
                Toast.makeText(requireContext(), "请先选择音频文件", Toast.LENGTH_SHORT).show();
                return;
            }
            if (btnVoice.getText().equals("播放中...")) {
                Toast.makeText(requireContext(), "正在播放，请稍后", Toast.LENGTH_SHORT).show();
                return;
            }

            try {
                // 初始化MediaPlayer
                android.media.MediaPlayer mediaPlayer = new android.media.MediaPlayer();

                // 设置音频源
                mediaPlayer.setDataSource(audioFile.getAbsolutePath());

                // 准备播放
                mediaPlayer.prepare();

                // 开始播放
                mediaPlayer.start();

                // 设置播放完成监听器
                mediaPlayer.setOnCompletionListener(mp -> {
                    mp.release(); // 播放完成后释放资源
                    btnVoice.setText("播放"); // 恢复按钮文字
                });

                btnVoice.setText("播放中..."); // 更新按钮文字



            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(requireContext(), "播放失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }

        });

        btnShare.setOnClickListener(v -> {
            //读取imageView中的图片并转化成 imageFile，将imageFile和audioFile一起作为参数创建shareFragment进行分享操作
            // 检查是否有图片和音频文件
            if (imageView.getDrawable() == null || audioFile == null) {
                Toast.makeText(requireContext(), "没有可分享的内容", Toast.LENGTH_SHORT).show();
                return;
            }

            // 获取图片文件路径
            imageView.buildDrawingCache();
            Bitmap bitmap = imageView.getDrawingCache();

            // 保存图片到缓存目录

            FragmentActivity activity = getActivity();
            if (activity != null) {
                // 执行 Fragment 切换
                FragmentManager fm=activity.getSupportFragmentManager();
                FragmentTransaction transaction = fm.beginTransaction();
                //隐藏所有的Fragment
                for (Fragment frag : fm.getFragments()) {
                    if (frag != null && frag.isAdded()) {
                        transaction.hide(frag);
                    }
                }
                Fragment existingFragment = fm.findFragmentByTag("ShareFragment");

                if (existingFragment != null) {
                    //从存储信息中更新
                    ((ShareFragment) existingFragment).setImageFile(outputFile);
                    ((ShareFragment) existingFragment).setAudioFile(audioFile);
                    transaction.show(existingFragment);
                } else {
                    // 创建新的 ShareFragment 实例
                    ShareFragment shoppingCartFragment = new ShareFragment(outputFile, audioFile);
                    transaction.add(R.id.FragmentContainer, shoppingCartFragment, "ShareFragment");
                }
                transaction.commit();
            }

        });


        // 上传音频
        btnUpload.setOnClickListener(v -> {
            if (!isNetworkAvailable()) {
                tvStatus.setText("请检查网络连接");
                return;
            }

            progressBar.setVisibility(View.VISIBLE);
            if (audioFile != null) {
                progressBar.setProgress(0); // 重置进度
                uploadAudioFile(audioFile);
            }else {
            btnUpload.setEnabled(true);
            btnSelectAudio.setEnabled(true);

            progressBar.setVisibility(View.GONE);
            }
        });
        return view;
    }
    private void uploadAudioFile(File file)  {
//        // 1. 创建 OkHttpClient
//        OkHttpClient client = new OkHttpClient.Builder()
//                .connectTimeout(30, TimeUnit.SECONDS)  // 连接超时
//                .readTimeout(60, TimeUnit.SECONDS)     // 读取超时
//                .writeTimeout(60, TimeUnit.SECONDS)    // 写入超时
//                .build();
//
//        // 2. 构建 Multipart 请求体
//        RequestBody requestBody = new MultipartBody.Builder()
//                .setType(MultipartBody.FORM)
//                .addFormDataPart("audio", file.getName(),
//                        RequestBody.create(file, MediaType.parse("audio/*")))
//                .addFormDataPart("number", "1")
//                .addFormDataPart("size", String.valueOf(1024 * 1024))
//                .build();
//
//        // 3. 构建请求
//        Request request = new Request.Builder()
//                .url(URL)
//                .post(requestBody)
//                .build();
//
//
//
//        // 4. 异步执行请求
//        client.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                tvStatus.post(() -> tvStatus.setText("上传失败: " + e.getMessage()));
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                if (!response.isSuccessful()) {
//                    tvStatus.post(() -> tvStatus.setText("服务器错误: " + response.code()));
//                    return;
//                }
//
//                try {
//                    String responseData = response.body().string();
//                    JSONObject json = new JSONObject(responseData);
//                    String imageUrl = json.getString("image_url");
//                    String description = json.getString("description");
//
//                    tvStatus.post(() -> {
//                        tvStatus.setText(description);
//                        new DownloadImageTask().execute(imageUrl);
//                    });
//                } catch (Exception e) {
//                    tvStatus.post(() -> tvStatus.setText("解析失败: " + e.getMessage()));
//                }
//            }
//        });
        // 获取SharedPreferences实例
        SharedPreferences sharedPref = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);

        //如果没有获取到用户名和密码，则提示用户登录
        if (sharedPref.getString("username", null) == null || sharedPref.getString("password", null) == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
            builder.setTitle("提示")
                    .setMessage("请先登录")
                    .setPositiveButton("确定", (dialog, which) -> {
                        // 关闭对话框
                        dialog.dismiss();
                    })
                    .show();
            return;
        }
// 获取用户ID
        String username = sharedPref.getString("username", null);
        String password = sharedPref.getString("password", null);


        btnUpload.setEnabled(false);
        btnSelectAudio.setEnabled(false);
        // 1. 创建 OkHttpClient
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();

        // 2. 构建带有进度回调的 Multipart 请求体
        ProgressRequestBody fileBody = new ProgressRequestBody(file, MediaType.parse("audio/*"),
                (bytesWritten, totalBytes) -> {
                    int progress = (int) ((bytesWritten * 100) / totalBytes);
                    progressBar.post(() -> progressBar.setProgress(progress));
                });



            RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("audio", file.getName(), fileBody)
                .addFormDataPart("username",username)
                .addFormDataPart("password",password)
                .addFormDataPart("number", "1")
                .addFormDataPart("size", String.valueOf(1024 * 1024))
                .build();

        // 3. 构建请求
        Request request = new Request.Builder()
                .url(URL)
                .post(requestBody)
                .build();

        // 4. 异步执行请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                requireActivity().runOnUiThread(() -> {
                    tvStatus.setText("上传失败: " + e.getMessage());
                    progressBar.setProgress(0); // 重置进度条
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                requireActivity().runOnUiThread(() -> {
                    // 无论成功/失败，都要恢复按钮状态
                    btnUpload.setEnabled(true);
                    btnSelectAudio.setEnabled(true);
                    progressBar.setVisibility(View.GONE);
                });
                if (!response.isSuccessful()) {
                    requireActivity().runOnUiThread(() -> {
                        tvStatus.setText("服务器错误: " + response.code());

                        progressBar.setProgress(0); // 重置进度条
                    });
                    return;
                }

                try {
                    String responseData = response.body().string();
                    JSONObject json = new JSONObject(responseData);

                    String imageUrl = json.has("image_url") ? json.getString("image_url") : null;
                    String description = json.has("description") ? json.getString("description") : null;
                    if (imageUrl == null || description == null) {
                        String message= json.has("message") ? json.getString("message") : "服务器返回数据错误，请联系客服";
                        requireActivity().runOnUiThread(() -> {
                            tvStatus.setText(message);
                            progressBar.setProgress(0); // 重置进度条
                        });
                        return;
                    }
                    requireActivity().runOnUiThread(() -> {
                        tvStatus.setText(description);
                        progressBar.setProgress(100); // 上传完成
                        new DownloadImageTask().execute(imageUrl);
                    });
                } catch (Exception e) {
                    requireActivity().runOnUiThread(() -> {
                        tvStatus.setText("解析失败: " + e.getMessage());
                        progressBar.setProgress(0); // 重置进度条
                    });
                }
            }
        });
    }
    // 检查网络是否可用
    private boolean isNetworkAvailable() {
        ConnectivityManager manager = (ConnectivityManager) requireContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnected();
    }

    // 异步下载图片任务
    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... urls) {
            try {
                URL url = new URL(urls[0]);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();
                InputStream input = connection.getInputStream();
                // 读取输入流并保存到文件
                // 获取公共的Pictures目录
                File picturesDir = Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES);

                // 如果目录不存在则创建
                if (!picturesDir.exists()) {
                    picturesDir.mkdirs();
                }
                String baseFileName = audioFile.getName().replaceFirst("[.][^.]+$", "");
                String fileName = generateUniqueFileName(picturesDir, generateUniqueFileName(picturesDir, baseFileName, ".jpg"), ".jpg");
                outputFile = new File(picturesDir, fileName);
                try (OutputStream output = new FileOutputStream(outputFile)) {
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = input.read(buffer)) != -1) {
                        output.write(buffer, 0, bytesRead);
                    }
                }
                // 通知系统扫描新文件
                MediaScannerConnection.scanFile(requireContext(), new String[]{outputFile.getAbsolutePath()}, null, null);
                // 关闭输入流
                input.close();
                // 返回文件路径
                return BitmapFactory.decodeFile(outputFile.getAbsolutePath());
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null) {
                imageView.setImageBitmap(bitmap);
                btnShare.setVisibility(View.VISIBLE);
            } else {
                tvStatus.setText("图片加载失败");
            }
        }
    }
    private String generateUniqueFileName(File directory, String baseName, String extension) {
        String fileName = baseName + extension;
        if (!new File(directory, fileName).exists()) {
            return fileName;
        }

        // 处理重名文件
        int n = 1;
        while (true) {
            fileName = baseName + "(" + n + ")" + extension;
            if (!new File(directory, fileName).exists()) {
                return fileName;
            }
            n++;
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_AUDIO_PICK && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {
                    String fileName = getFileNameFromUri(uri);
                    audioFile =  uriToFile(uri);
                    tvStatus.setText("已选择: " + fileName);
                    btnUpload.setEnabled(true);
                }
            }
        }
    }
    private File uriToFile(Uri uri) {
        btnVoice.setVisibility(View.VISIBLE);
        // 先尝试直接获取路径
        if ("file".equalsIgnoreCase(uri.getScheme())) {
            return new File(uri.getPath());
        }

        // 对于content:// Uri，需要复制到缓存目录
        String fileName = getFileNameFromUri(uri);
        if (fileName == null) {
            fileName = "audio_" + System.currentTimeMillis();
        }

        File cacheDir = requireContext().getCacheDir();
        File outputFile = new File(cacheDir, fileName);

        try (InputStream in = requireContext().getContentResolver().openInputStream(uri);
             OutputStream out = new FileOutputStream(outputFile)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            return outputFile;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 从Uri获取文件名
     */
    private String getFileNameFromUri(Uri uri) {
        String displayName = "audio_" + System.currentTimeMillis(); // 默认文件名

        // 先尝试通过DISPLAY_NAME列获取
        try (Cursor cursor = requireContext().getContentResolver().query(
                uri, null, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                // 安全获取列索引
                int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                if (nameIndex >= 0) {
                    displayName = cursor.getString(nameIndex);
                } else {
                    // 如果DISPLAY_NAME列不存在，尝试其他方式
                    displayName = getFileNameFallback(uri, cursor);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return displayName;
    }
    private String getFileNameFallback(Uri uri, Cursor cursor) {
        // 方案1：尝试从URI最后一段获取
        String fileName = uri.getLastPathSegment();
        if (fileName != null && !fileName.isEmpty()) {
            // 去除可能包含的路径部分
            int cut = fileName.lastIndexOf('/');
            if (cut != -1) {
                fileName = fileName.substring(cut + 1);
            }
            return fileName;
        }

        // 方案2：遍历所有列尝试找到文件名
        for (String columnName : cursor.getColumnNames()) {
            if (columnName.toLowerCase().contains("name") ||
                    columnName.toLowerCase().contains("display")) {
                int index = cursor.getColumnIndex(columnName);
                if (index >= 0) {
                    String name = cursor.getString(index);
                    if (name != null && !name.isEmpty()) {
                        return name;
                    }
                }
            }
        }

        // 方案3：使用数据列作为最后手段
        int dataIndex = cursor.getColumnIndex("_data");
        if (dataIndex >= 0) {
            String path = cursor.getString(dataIndex);
            if (path != null) {
                return new File(path).getName();
            }
        }

        // 所有方案都失败，返回默认名称
        return "audio_" + System.currentTimeMillis();

    }

    // 处理权限请求结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CODE_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openFilePicker();
            } else {
                Toast.makeText(requireContext(), "需要存储权限才能选择文件", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void openFilePicker() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("audio/*"); // 选择音频文件
        // 确保有应用可以处理这个Intent
        if (intent.resolveActivity(requireActivity().getPackageManager()) != null) {
            startActivityForResult(intent, REQUEST_CODE_AUDIO_PICK);
        } else {
            Toast.makeText(requireContext(), "没有可用的文件管理器", Toast.LENGTH_SHORT).show();
        }
    }
    public static SecondFragment newInstance() {
        return new SecondFragment();
    }
}
